package com.cjm.one.common.config.jackson;

import com.cjm.one.model.base.BaseEnum;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

@Configuration
public class EnumConverterConfig implements WebMvcConfigurer {
    
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 添加通用枚举转换器
        registry.addConverterFactory(new StringToBaseEnumConverter());
    }

    public static class StringToBaseEnumConverter implements ConverterFactory<String, BaseEnum> {
        @Override
        public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
            return source -> Arrays.stream(targetType.getEnumConstants())
                    .filter(e -> String.valueOf(e.getCode()).equals(source))
                    .findFirst()
                    .orElseGet(() -> getDefaultValue(targetType));
        }

        private <T extends BaseEnum> T getDefaultValue(Class<T> enumType) {
            return Arrays.stream(enumType.getEnumConstants())
                    .filter(e -> e.getClass().isAnnotationPresent(JsonEnumDefaultValue.class))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("无默认枚举值"));
        }
    }
}
